package cn.unknowpupil.init.common.service;

import cn.unknowpupil.init.common.enums.ResultStatus;
import cn.unknowpupil.init.domain.dto.LoginUser;
import cn.unknowpupil.init.domain.system.SysUser;
import cn.unknowpupil.init.exceptions.HealthException;
import cn.unknowpupil.init.service.system.ISysUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * Created at 2020/12/3 by w10g <br>
 * Initialize JwtUserDetailsService ... <br>
 *
 * @author unknowpupil
 * @since 0.0.1
 */
@Slf4j
@Service
public class JwtUserDetailsService implements UserDetailsService {
    @Autowired
    private ISysUserService userService;

    @Override
    public LoginUser loadUserByUsername(String username) {
        log.info("{}：经过密码登录认证。。。。",username);
        SysUser sysUser = userService.getUserByUsername(username);
        if(sysUser==null){
            throw new HealthException(ResultStatus.USER_PASSWORD_ERROR);
        }
        List<GrantedAuthority> auths = new ArrayList<>();
        auths.add(new SimpleGrantedAuthority("ACTIVITI_USER"));
//        String[][] usersGroupsAndRoles = {
//                             {"salaboy", "password", "ROLE_ACTIVITI_USER", "GROUP_activitiTeam"},
//                             {"ryandawsonuk", "password", "ROLE_ACTIVITI_USER", "GROUP_activitiTeam"},
//                             {"erdemedeiros", "password", "ROLE_ACTIVITI_USER", "GROUP_activitiTeam"},
//                             {"other", "password", "ROLE_ACTIVITI_USER", "GROUP_otherTeam"},
//                             {"admin", "password", "ROLE_ACTIVITI_ADMIN"},
//                     };
//        List<String> authoritiesStrings= Lists.newArrayList();
//        for (String[] user  : usersGroupsAndRoles) {
//            authoritiesStrings = Arrays.asList(Arrays.copyOfRange(user, 2, user.length));
//
//        }
//        List<SimpleGrantedAuthority> collect = authoritiesStrings.stream().map(s -> new SimpleGrantedAuthority(s)).collect(Collectors.toList());

        return new LoginUser(sysUser.getId(),sysUser.getPid(),username,sysUser.getPassword(),sysUser.isAdmin(),auths);
    }

}
